//
//  IFlyDebugLog.m
//  AIKITDemo
//
//  Created by xyzhang on 2023/3/1.
//

#import "IFlyDebugLog.h"

/*!
 *  去除获取文件的路径和文件名后缀
 *
 *  @param filePath 文件路径
 *
 *  @return 文件名（无后缀）
 */
NSString* __IFlyLogTrimFilePath__(char* filePath){
    NSString* fileName = [NSString stringWithFormat:@"%s", filePath];
    return  [[fileName lastPathComponent] stringByDeletingPathExtension];
}

static BOOL isShowLog = YES;
static NSString *logPath  = nil;
static NSMutableArray *logArray = nil;
static NSFileHandle *inFile = nil;

@implementation IFlyDebugLog

+ (void)showLog:(NSString *)format, ... {
    if ( isShowLog) {
        va_list args;
        va_start(args, format);
        NSString *str = [[NSString alloc] initWithFormat:format arguments:args];
        va_end(args);
        NSLog(@"[IFLYTEK] %@",str);
        
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"IFlyDebugLog" object:nil userInfo:@{@"logStr":[NSString stringWithFormat:@"[CONSOLE] %@\n", str]}];
        
    }
}

+ (void)consoleLog:(NSString *)format, ... {
    if ( isShowLog) {
        va_list args;
        va_start(args, format);
        NSString *str = [[NSString alloc] initWithFormat:format arguments:args];
        va_end(args);
        NSLog(@"[IFLYTEK] %@",str);
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"IFlyDebugLog" object:nil userInfo:@{@"logStr":[NSString stringWithFormat:@"[CONSOLE] %@\n", str]}];
    }
}


+ (void)setShowLog:(BOOL)showLog {
    isShowLog = showLog;
}
/*
 * @将系统时间和打印的日志组合，然后写入数组中
 */
+ (void)addString:(NSString *)str {
    NSDate *nowDate = [NSDate date];
    NSString *log = [NSString stringWithFormat:@"%@---%@\n",nowDate,str];
    [logArray addObject:log];
    
}

+ (void)createFile {
    NSArray *appArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    if ([appArray count] > 0) {
        NSString *docPath = [appArray objectAtIndex:0];
        logPath = [docPath stringByAppendingPathComponent:@"msc_ios.log"];
        // 判断文件是否存在
        NSFileManager *fileManager =  [NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath:logPath]) {
            [fileManager createFileAtPath:logPath contents:nil attributes:nil];
        }
        
        inFile = [NSFileHandle fileHandleForWritingAtPath:logPath];
    }
}

/*
 * @将log写入文件
 */
+ (void)writeLog {
    if (logPath == nil) {
        [IFlyDebugLog createFile];
    }
    
    // 定位到文件末尾
    [inFile seekToEndOfFile];
    
    for (int i = 0; i < [logArray count]; i++) {
        NSString *log = [logArray objectAtIndex: i];
        [inFile writeData: [log dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    [inFile closeFile];
    
    [logArray removeAllObjects];
}

@end
